//
//  RepaymentViewController.swift
//  IDF
//
//  Created by 陈徐挺 on 30/03/2018.
//  Copyright © 2018 Jesse.chen. All rights reserved.
//

import UIKit
import ALCameraViewController
import AliyunOSSiOS
import Kingfisher
import PromiseKit
import SVProgressHUD

class RepaymentViewController: BaseViewController {

    var record: Record!

    var isExtend: Bool = false
    
    @IBOutlet weak var label_1: UILabel!
    @IBOutlet weak var label_2: UILabel!
    @IBOutlet weak var label_3: UILabel!
    @IBOutlet weak var label_4: UILabel!
    @IBOutlet weak var label_5: UILabel!
    @IBOutlet weak var label_6: UILabel!
    @IBOutlet weak var label_7: UILabel!
    @IBOutlet weak var label_8: UILabel!
    
    @IBOutlet weak var certificateBtn: UIButton!
    @IBOutlet weak var certificateImageView: UIImageView!
    @IBOutlet weak var delCertificateImage: UIButton!
    @IBOutlet weak var delCertificateBtn: UIButton!

    @IBOutlet weak var saveButtonView: FooterButtonView!

    var libraryEnabled: Bool = true
    var croppingEnabled: Bool = false
    var allowResizing: Bool = true
    var allowMoving: Bool = false
    var minimumSize: CGSize = CGSize(width: kWidth - 30 - 30, height: (kWidth - 30 - 30) * 5 / 9)

    var croppingParameters: CroppingParameters {
        return CroppingParameters(isEnabled: croppingEnabled, allowResizing: allowResizing, allowMoving: allowMoving, minimumSize: minimumSize)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        label_3.text = "NO. \(record.debitId!)"
        label_1.text = "Rp\(record.debitMoney!)"
        label_2.text = "\(record.debitPeroid!) Days"
        label_4.text = "Loan term: \(record.releaseLoanTime!)"
        label_5.text = "create time: \(record.createTime!)"
        label_6.text = "Rp\(record.payBackMoney!)"
        label_8.text = "Upload bank receipt of payback infomation"
        certificateImageView.isHidden = true
        delCertificateBtn.isHidden = true
        delCertificateImage.isHidden = true
        record.certificate = ""
        saveButtonView.doneButton.setTitle("Submit", for: .normal)
        if isExtend {
            extendDataLoad()
        }
        // Do any additional setup after loading the view.
        var title = "Submit pay back"
        if isExtend {
            title = "Submit extend"
        }
        saveButtonView.doneButton.setBlockFor(.touchUpInside) { [weak self] (button) in
            EZAlertController.alert(title, message: "", buttons: ["Give up", "Submit"], tapBlock: { (_, index) in
                if index == 1 {
                    SVProgressHUD.show()
                    let _ = self?.saveImage().then { _ -> Void in
                        if (self?.isExtend)! {
                            let _ = self?.record.submitExtendReuqest().then { _ -> Void in
                                let submitted2View = Submitted2View(frame: appWindow.bounds)
                                appWindow.addSubview(submitted2View)
                            }
                        } else {
                            let _ = self?.record.submitPayBackDebitReuqest().then { _ -> Void in
                                let submitted2View = Submitted2View(frame: appWindow.bounds)
                                appWindow.addSubview(submitted2View)
                            }
                        }
                    }
                }
            })
        }
    }

    func extendDataLoad() {
        SVProgressHUD.show()
        label_7.text = "Need to payback Extension Fee"
        label_8.text = "Scan bank receipt of Extension Fee"
        let request = RequestData(path: "Debit/GetUserExtendInfo", method: .get, param: ["debitId": record.debitId])
        netRequest(request).then{[weak self] json -> Void in
            dPrint(json)
            self?.label_4.text = "Extend another \(json["debitPeroid"].stringValue) days"
            self?.label_6.text = "Rp \(json["extendFee"].stringValue)"
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func delImage(_ sender: UIButton) {
        certificateImageView.isHidden = true
        certificateBtn.isEnabled = true
        delCertificateImage.isHidden = true
        delCertificateBtn.isHidden = true
        record.certificate = ""
    }


    @IBAction func uploadCertificate(_ sender: UIButton) {
        let cameraViewController = CameraViewController(croppingParameters: croppingParameters, allowsLibraryAccess: false, allowsSwapCameraOrientation: true, allowVolumeButtonCapture: true) { [weak self] image, asset in
            if let img = image {
                self?.certificateImageView.image = img.byRotateLeft90()
                self?.certificateImageView.isHidden = false
                self?.certificateBtn.isEnabled = false
                self?.delCertificateBtn.isHidden = false
                self?.delCertificateImage.isHidden = false
            }
            self?.dismiss(animated: true, completion: nil)
        }
        present(cameraViewController, animated: true, completion: nil)
    }


    func saveImage() -> Promise<Void> {
        var promiseArr: [Promise<String>] = []
        if record.certificate == "", let img = certificateImageView.image {
            promiseArr.append(uploadImg(UIImageJPEGRepresentation(img, 0.2)!, key: "\(record.debitId!)_certificate"))
        }
        return when(fulfilled: promiseArr).then { [weak self] stringArr -> Promise<Void> in
            let _ = stringArr.map { url -> Void in
                if url.hasSuffix("_certificate.jpg") {
                    self?.record.certificate = url
                }
            }
            return Promise(value: ())
        }
    }

    func uploadImg(_ data: Data, key: String) -> Promise<String> {
        let (wrappingPromise, fulfill, reject) = Promise<String>.pending()
        let put = OSSPutObjectRequest()
        put.bucketName = aliyunBucket
        put.objectKey = "\(appUser.userId!)_\(key).jpg"
        put.uploadingData = data
        let putTask = client.putObject(put)
        putTask.continue({ (task: OSSTask) -> Any? in
            if task.error == nil {
                let url = "https://\(aliyunBucket).\(aliyunEndpoint).com/\(put.objectKey)"
                fulfill(url)
            } else {
                dPrint(task.error!)
                reject(task.error!)
            }
            return nil
        }, cancellationToken: nil)
        return wrappingPromise
    }

    @IBAction func infoClick(_ sender: UIButton) {
        let loanfeesView = LoanfeesView(frame: appWindow.bounds)
        loanfeesView.label_1.text = "Rp\(record.debitMoney!)"
        loanfeesView.label_2.text = "Rp\(record.dayInterset!)"
        loanfeesView.label_3.text = "\(record.debitPeroid!)"
        loanfeesView.label_4.text = "Rp\(record.payBackMoney!)"
        if record.overdueDay! == 0 {
            loanfeesView.label_5.removeFromSuperview()
            loanfeesView.label_6.removeFromSuperview()
            loanfeesView.label_7.removeFromSuperview()
            loanfeesView.label_8.removeFromSuperview()
            loanfeesView.viewHeight.constant = 330
        } else {
            loanfeesView.label_6.text = "Rp\(record.dayInterset!)"
            loanfeesView.label_8.text = "\(record.overdueDay!)"
            loanfeesView.viewHeight.constant = 400
        }
        appWindow.addSubview(loanfeesView)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
